import { signal, Signal } from "@preact/signals"
import { PayloadFormatter } from "./format"
import { createLogger } from "./logger"

const logger = createLogger("signalWithStorage")
/**
 * 創建一個與 localStorage 同步的 Signal
 * @param initialValue 初始值
 * @param key 存儲鍵名
 * @returns Signal 實例
 */
export function signalWithStorage<T>(initialValue: T, key: string): Signal<T> {
    // 嘗試從 localStorage 讀取值
    let storedValue: T | null = null
    try {
        const stored = localStorage.getItem(key) as string | null
        const storedDecoded = stored
            ? (PayloadFormatter.decode(stored) as unknown as { data: T })
            : null
        if (storedDecoded) {
            storedValue = storedDecoded.data
        }
    } catch {
        // 解析錯誤時使用初始值
    }

    const s = signal<T>(storedValue !== null ? storedValue : initialValue)
    s.subscribe((value) => {
        localStorage.setItem(key, PayloadFormatter.encode({ data: value }))
    })

    return s
}
